package server.performance;

import iface.Envelope;
import iface.Logger;
import iface.MessageInterface;
import iface.Registration;
import iface.Status;
import iface.UserTypes;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;

public class ClientLoadTest {
    private static final boolean REGISTER_NEW_USERS = true;
    private static final Random r = new Random();
    private static final int LOC_FREQ = 5;
    private static final int N_CLIENTS = 20;
    private static final UserTypes ZOMBIE_CLIENTS = UserTypes.ZOMBIE;
    private static List<String> regedUsers = new ArrayList<String>(N_CLIENTS);
    private static List<Timer> locTimers = new ArrayList<Timer>();

    public static void main(String args[]) {

        // Register N unique clients in the database for future testing.
        if (REGISTER_NEW_USERS)
            batchRegisterUsers();

        Logger.log("Reg'd users: ");
        for (String user : regedUsers)
            Logger.log(user);

        spawnLocationThreads();
    }

    private static void spawnLocationThreads() {
        int i = 0;
        while ((i + 2) <= N_CLIENTS) {
            SendLocations sl = new SendLocations(regedUsers.subList(i, i + 2));
            Timer t = new Timer();
            t.schedule(sl, 0, LOC_FREQ * 1000);
            locTimers.add(t);
            i += 2;
        }
    }

    private static String getRandPhoneNum() {
        String phone = "";
        for (int i = 0; i < 10; i++) {
            phone += r.nextInt(9);
            if (i == 2 || i == 5)
                phone += "-";
        }
        return phone;
    }

    public static void batchRegisterUsers() {
        int reged = 0;
        String user, phone;
        while (reged < N_CLIENTS) {
            user = "user" + r.nextInt();
            phone = getRandPhoneNum();
            if (regUser(user, phone)) {
                regedUsers.add(user);
                reged++;
            } else {
                Logger.log("Unable to reg: <" + user + ", " + phone + ">");
            }
        }
    }

    public static boolean regUser(String username, String phone) {
        // Attempt to register user in the database.
        Registration reg = new Registration(username, ZOMBIE_CLIENTS, phone);
        Envelope env = new Envelope("perf-test", reg);
        Logger.verbose("Send reg msg for " + username);
        Status status = MessageInterface.sendEnvelopeToServer(env);
        Logger.verbose("Recv'd reg msg for " + username);

        // If we were unable to register, indicate this to the caller.
        return status.getMessageStatus().equals(Status.Result.SUCCESS);
    }

}
